package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtTokenProperties jwtTokenProperties;

    /**
     * 用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        //根据用户名查询用户
        User user = userMapper.selectByUsername(loginDto.getUsername());
        //判断用户是否为空
        if (ObjectUtil.isEmpty(user)) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }

        //判断密码是否正确
        if (!BCrypt.checkpw(loginDto.getPassword(), user.getPassword())) {
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }

        //判断用户是否被禁用 1禁用 0启用
        if (StrUtil.equals(user.getDataState(), "1")) {
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }


        //对象转换
        LoginVo loginVo = BeanUtil.toBean(user, LoginVo.class);

        //密码脱敏
        loginVo.setPassword("");

        //根据用户生成JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", loginVo.getId());

        String token = JwtUtil.createJWT(jwtTokenProperties.getSecretKey(),
                jwtTokenProperties.getTtl(), claims);
        loginVo.setUserToken(token);

        return loginVo;
    }
}